package com.zzl.springboot_mybatis_demo.task;

import com.zzl.springboot_mybatis_demo.job.CancelOrderJob;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

/**
 * description: 取消订单执行类
 * @author 朱正磊
 * @date 2020-06-20 21:06:48
 */
@Slf4j
public class CancelOrderTask {

    public void cancelOrderTask() throws SchedulerException {
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        JobDetail jobDetail = JobBuilder.newJob(CancelOrderJob.class)
                .withIdentity("cancelOrderJob", "orderJob")
                .storeDurably()
                .build();

        scheduler.addJob(jobDetail, false);

        // 创建一个简单触发器，当启动项目时立即执行，
        // CronTrigger的startNow()方法在设定定时任务后不起作用
        Trigger simpleTrigger = TriggerBuilder.newTrigger()
                .withIdentity("firstCancelOrderTrigger", "firstOrderTrigger")
                .startNow()
                .forJob("cancelOrderJob", "orderJob")
                .build();

        // 触发器加入到scheduler
        scheduler.scheduleJob(simpleTrigger);

        // 创建一个CronTrigger触发器，设定触发时间
        // CronTrigger触发器startNow没有任何作用，因为有自己的触发时间
        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity("cancelOrderTrigger", "orderTrigger")
                //触发时间（轮询时间）
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0/2 * * * ?"))
                //触发器绑定job
                .forJob("cancelOrderJob", "orderJob").build();

        // 将job和触发器绑定
        scheduler.scheduleJob(cronTrigger);

        String logInfo = jobDetail.getKey() + "取消订单任务定时器启动";
        log.info(logInfo);
        System.out.println(logInfo);
        scheduler.start();
    }

}
